package com.ruoyi.system.utils;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.io.IOUtils;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.OutputStream;

public class MultipartFileUtil {

    public static MultipartFile getMultipartFile(String name, byte[] bytes) {
        if (bytes == null || name == null) {
            throw new IllegalArgumentException("File name and byte array must not be null");
        }

        FileItemFactory factory = new DiskFileItemFactory();
        FileItem fileItem = factory.createItem("mainFile", "text/plain", false, name);

        try (OutputStream os = fileItem.getOutputStream();
             ByteArrayInputStream in = new ByteArrayInputStream(bytes)) {
            IOUtils.copy(in, os);
        } catch (IOException e) {
            throw new RuntimeException("Error creating MultipartFile", e);
        }

        return new CommonsMultipartFile(fileItem) {
            public void delete() {
                fileItem.delete(); // 手动删除文件，释放资源
            }
        };
    }
}
